<%@ Application Language="VB" %>

<%@ Import Namespace="System.Web.Profile" %>
<%@ Import Namespace="Wrox.Web.GlobalEvents" %>

<script runat="server">

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup
    End Sub
    
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application shutdown
    End Sub
        
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        
        Dim ex As Exception = Server.GetLastError()
        
        Tools.Log("An unhandled error was caught by Application_Error", ex)
        
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a new session is started
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a session ends. 
        ' Note: The Session_End event is raised only when the sessionstate mode
        ' is set to InProc in the Web.config file. If session mode is set to StateServer 
        ' or SQLServer, the event is not raised.
    End Sub

    Public Sub Profile_OnMigrateAnonymous(ByVal Sender As Object, ByVal e As ProfileMigrateEventArgs)
    
        ' get the profile for the anonymous user
        Dim anonProfile As ProfileCommon = Profile.GetProfile(e.AnonymousID)

        ' if they have a shopping cart, then migrate that to the authenticated user
        If anonProfile.Cart IsNot Nothing Then

            If Profile.Cart Is Nothing Then
                profile.Cart = New Wrox.Commerce.ShoppingCart()
                profile.Cart.Items.AddRange(anonProfile.Cart.Items)
            end if
            
            anonProfile.Cart = Nothing
        End If

        ProfileManager.DeleteProfile(e.AnonymousID)
        AnonymousIdentificationModule.ClearAnonymousIdentifier()

    End Sub
    
</script>